'use strict';

const dataConst = require('../constant/data-const');
const Service = require('egg').Service;

class MessageService extends Service {
    async createMessageSrv(userId, targetUserId, type, content) {
        const { app } = this;

        const result = await app.model.MemberMessage.create({
            user_id: userId,
            target_user_id: targetUserId,
            type,
            content
        });

        return await app.model.MemberMessage.findById(result.id);
    }

    async setMessageAsReadSrv(userId, targetUserId) {
        const { app } = this;

        return await app.model.MemberMessage.update({
            read_state: dataConst.msgReadType.read.value
        }, {
            where: {
                user_id: userId,
                target_user_id: targetUserId,
                state: dataConst.stateType.active
            }
        });
    }

    async shieldSendMessageSrv(messageId) {
        const { app } = this;

        return await app.model.MemberMessage.update({
            user_state: dataConst.stateType.inactive
        }, {
            where: {
                id: messageId
            }
        });
    }

    async shieldReceiveMessageSrv(messageId) {
        const { app } = this;

        return await app.model.MemberMessage.update({
            target_user_state: dataConst.stateType.inactive
        }, {
            where: {
                id: messageId
            }
        });
    }

    async shieldConversationSrv(userId, targetUserId) {
        const { app } = this;

        await app.model.MemberMessage.update({
            user_state: dataConst.stateType.inactive
        }, {
            where: {
                user_id: userId,
                target_user_id: targetUserId
            }
        });

        await app.model.MemberMessage.update({
            target_user_state: dataConst.stateType.inactive
        }, {
            where: {
                target_user_id: userId,
                user_id: targetUserId
            }
        });
    }

    async getMessageByIdSrv(messageId) {
        const { app } = this;

        return await app.model.MemberMessage.findOne({
            where: {
                id: messageId
            }
        });
    }

    async getChatMessageSrv({userId, targetUserId, limit = 8, offset = 0}) {
        const { ctx } = this;

        const queryString =
            `select
                *
                from tbl_member_message
                where true
                and (user_id = :userId or user_id = :targetUserId)
                and (target_user_id = :userId or target_user_id = :targetUserId)
                and if(user_id = :userId, user_state, target_user_state) = :state
                order by created_at desc`;

        const paramsData = {userId, targetUserId, state: dataConst.stateType.active};
        return await ctx.helper.sqlQueryCount(queryString, paramsData, limit, offset);
    }

    async getUserMessageListSrv({userId, limit = 8, offset = 0}) {
        const { ctx } = this;

        const queryString =
            `select
                usr.id, usr.nickname, usr.avatar
                , if(isnull(usr.avatar) || length(trim(usr.avatar)) < 1, null, concat(:serverUrl, :avatarPath, usr.id, '/', usr.avatar)) as avatar_url
                , timestampdiff(year, usr.birthday, curdate()) as age
                , ub.body_height, ub.education_id, ub.month_pay, ub.live_region, ub.marriage_state
                , cvl.unread_count, cvl.latest_time
                from tbl_user usr
                left join tbl_user_base ub
                on usr.id = ub.user_id
                inner join (
                select
                cv.target_user_id, sum(cv.unread_count) as unread_count, max(latest_time) as latest_time
                from (
                select
                if(mm.user_id = :userId, mm.user_id, mm.target_user_id) as user_id
                , if(mm.target_user_id = :userId, mm.user_id, mm.target_user_id) as target_user_id
                , sum(if(mm.user_id = :userId, 0, read_state)) as unread_count
                , max(created_at) as latest_time
                from tbl_member_message mm
                where true
                and state = :state
                and (mm.user_id = :userId or mm.target_user_id = :userId)
                and if(mm.user_id = :userId, mm.user_state = :state, mm.target_user_state = :state)
                group by user_id, target_user_id) cv
                group by cv.target_user_id) cvl
                on usr.id = cvl.target_user_id
                where usr.state = :state
                order by latest_time desc`;

        const paramsData = {
            serverUrl: dataConst.serverUrl,
            avatarPath: dataConst.avatarPath,
            userId,
            state: dataConst.stateType.active
        };
        return await ctx.helper.sqlQueryCount(queryString, paramsData, limit, offset);
    }
}

module.exports = MessageService;
